package com.lottery.system.common.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: xiaoxie
 * create: 2024-09-05 11:52
 * @BelongsProject: lottery-system
 * @BelongsPackage: com.lottery.system.common.utils
 * description: JWT令牌工具包
 */
public class JwtUtil {
    private final static Logger logger = LoggerFactory.getLogger(JwtUtil.class);
    //过期毫秒时⻓12小时
    public static final long EXPIRATION_TIME=12*60*60*1000;
    //密钥
    private static final String SECRET_STRING="kgcutTW90zvNRToLYtgf1uJ19V85HwBDRw9M7hFcrZg=";
    // ⽣成安全密钥
    private static final SecretKey KEY =
            Keys.hmacShaKeyFor(Decoders.BASE64.decode(SECRET_STRING));

    /**
     * @description: 生成Token
     * @author: xiaoxie
     * @date: 2024/9/5 12:03
     * @param: [claims]
     * @return: java.lang.String
     **/
    public static String generateToken(Map<String, Object> claims) {
       return Jwts.builder().setClaims(claims)
                     .setIssuedAt(new Date())
                     .setExpiration(new Date(System.currentTimeMillis()+EXPIRATION_TIME))
                     .signWith(KEY)
                     .compact();
    }
    /**
     * @description: 校验Token
     * @author: xiaoxie
     * @date: 2024/9/5 12:06
     * @param: [token]
     * @return: io.jsonwebtoken.Claims
     **/
    public static Claims verifyToken(String token) {
        if (!StringUtils.hasLength(token)){
            return null;
        }
        // 创建解析器, 设置签名密钥
        JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder().setSigningKey(KEY);
        Claims claims = null;
        try {
            //解析token
            claims = jwtParserBuilder.build().parseClaimsJws(token).getBody();
        }catch (Exception e){
            // 签名验证失败
            logger.error("解析令牌错误,jwt:{}", token, e);
        }
        return claims;
    }
    /**
     * @description: 从token中获取用户ID
     * @author: xiaoxie
     * @date: 2024/9/5 12:07
     * @param: [jwtToken]
     * @return: java.lang.Integer
     **/
    public static Integer getUserIdFromToken(String jwtToken) {
        Claims claims = JwtUtil.verifyToken(jwtToken);
        if (claims != null) {
            Map<String, Object> userInfo = new HashMap<>(claims);
            return (Integer) userInfo.get("userId");
        }
        return null;
    }
}
